#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''xls表格导出为markdown表格字符串

历史:
    2019-01-02 姚彧 移植
'''

import os
import sys
import xlrd
import pyperclip

def cell_get_value(cell, cell_type, EPS = 0.00001):
    if cell_type == xlrd.XL_CELL_NUMBER:
        v = int(cell)
        if abs(v - v) < EPS:
            return str(v)
        else:
            return '%.3f' % cell
    return cell.replace('\r', '\n').replace('\n\n', '\n').replace('\n', '<br>')

def xls2md(xls_file, start_row = 0, start_col = 0, header_rows = 1):
    assert os.path.isfile(xls_file), xls_file
    assert start_row >= 0
    assert start_col >= 0
    assert header_rows >= 0
    def toTableRow(row):
        return '| %s |' % ' | '.join(row)

    wb = xlrd.open_workbook(xls_file)
    sheet = wb.sheets()[0]
    cell_values = sheet._cell_values
    cell_types = sheet._cell_types
    if start_row > 0:
        cell_values = cell_values[start_row:]
        cell_types = cell_types[start_row:]
    rows = []
    for i, row in enumerate(cell_values):
        rows.append(tuple(zip(row[start_col:], cell_types[i][start_col:])))
    headers, rows = rows[:header_rows], rows[header_rows:]
    res = []
    for row in headers:
        res.append(toTableRow([i[0] for i in row]))
    res.append(toTableRow(['-'] * len(headers[0])))
    for row in rows:
        res.append(toTableRow([cell_get_value(*i) for i in row]))
    content = '\n'.join(res)
    print(content)
    pyperclip.copy(content)


def main(argv):
    if len(argv) < 2:
        print('命令行调用方式:\npython xls2md.py xls文件名 起始行 起始列 标题行数')
        return
    xls_file = argv[1]
    start_row = 0
    start_col = 0
    header_rows = 1
    try:
        start_row = int(argv[2]) - 1
        start_col = int(argv[3]) - 1
        header_rows = int(argv[4])
    except:
        pass
    if start_row < 0:
        start_row = 0
    if start_col < 0:
        start_col = 0
    if header_rows < 1:
        header_rows = 1
    xls2md(xls_file, start_row, start_col, header_rows)


if __name__ == '__main__':
    main(sys.argv)
